const express = require('express');
const router = express.Router();
const multer = require('multer');
const fs = require('fs')
const path = require('path')
const cheerio = require('cheerio')
const { parseDocument } = require('htmlparser2')
let htmlFileName = null
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/files/') // 设置上传文件保存的目录
  },
  filename: function (req, file, cb) {
    let name = Date.now() + '-' + file.originalname
    if (file.originalname.includes('html')) {
      htmlFileName = name
    } else {
      fileName = name
    }
    cb(null, name) // 设置文件名，这里用时间戳加原始文件名避免重名
  }
});
const upload = multer({ storage: storage });

router.post('/', upload.fields([{ name: 'htmlFile', maxCount: 1 }]), (req, res) => {
  if (!req.files.htmlFile&&!req.body.attrs) {
    return res.status(400).send('No file uploaded.');
  }

  fs.readFile(path.join(process.cwd(), 'public/files/' + htmlFileName), 'utf8', (err, data) => {
    if (err) {
      console.error('读取文件时发生错误:', err);
      return;
    }
    const jquery = cheerio.load(data);
    const standardAttrs  = req.body.attrs.split(',')
    standardAttrs.forEach(i => {
      jquery(`[${i}]`).removeAttr(i) 
    })
    res.send({
      code: 200,
      msg: "sucess",
      data: jquery.html(),
    });
  });
})
module.exports = router